package com.tanhua.dubbo.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class IdService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 计算自增长的id
     *
     * @param type 类型：动态、视频
     * @param publishId 动态、视频发布的id
     * @return 自增长的id
     */
    public Long createId(String type, String publishId) {
        type = StringUtils.upperCase(type);

        String idHashKey = "TANHUA_ID_HASH" + type;
        // 判断redis中是否已经存在动态对应的自增长id，如果存在，返回这个自增长id
        if (redisTemplate.opsForHash().hasKey(idHashKey, publishId)) {
            return Long.valueOf(String.valueOf(redisTemplate.opsForHash().get(idHashKey,publishId)));
        }

        //如果不存在，让这个key自增1，并把计算出来的值，添加到redis中，并返回
        String idKey = "TANHUA_ID_" + type;
        Long id = this.redisTemplate.opsForValue().increment(idKey);

        this.redisTemplate.opsForHash().put(idHashKey, publishId, id.toString());

        return id;
    }
}
